package com.tianyadu.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyadu.security.browser.dto.BaseResponse;
import com.tianyadu.security.core.properties.SecurityProperties;
import com.tianyadu.security.core.properties.propertieVO.LoginResponseType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: AuthFailureHandler
 * @Description:
 * @author: xueyj
 * @create: 2018-12-09 17:42
 */
@Slf4j
@Component
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
      * @Description: 登陆认证失败处理
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/10 18:01
      */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        log.info("登录失败");

        // 判断是用哪一种方式进行登录的
        // 如果是JSON，则返回JSON字符串；否则进行页面的跳转
       if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            //   http请求状态码（500）
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            //  设置响应信息的格式及字符编码
            response.setContentType("application/json;charset=UTF-8");
            //  将响应异常信息写入至response
            response.getWriter().write(objectMapper.writeValueAsString(new BaseResponse(exception.getMessage())));
       } else {
            super.onAuthenticationFailure(request, response, exception);
       }
    }
}